<template>
  <div>
    <el-row>
      <el-col style="margin-top: 10px">
        <el-input
          v-model="search"
          style="width: 240px"
          placeholder="请输入药名"
        />
        <el-button style="margin-left: 20px" type="primary">搜索</el-button>
        <el-button
          style="margin-left: 20px"
          type="primary"
          @click="
            add_yaopin();
            dialogVisible = true;
          "
          >添加药品</el-button
        >
      </el-col>

      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="Data"
          :stripe="true"
          :border="true"
          :fit="true"
        >
          <el-table-column
            prop="Name"
            label="药品名称"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="Dtc"
            label="药品编号"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>

          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="auto"
          >
            <template #default="scope">
              <!-- <el-button
                link
                type="primary"
                size="small"
                @click="
                  info(scope.row);
                  dialogVisible = true;
                "
                >详情</el-button
              > -->
              <el-button
                link
                type="primary"
                size="small"
                style="color: red"
                @click="del(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <el-dialog
        v-model="dialogVisible"
        title="添加药品"
        width="50%"
        :before-close="handleClose"
      >
        <el-form :model="form" label-position="right" ref="ruleFormRef"  :rules="rules">
          <el-form-item label="药品名:" label-width="150px"  prop="Name">
                 <el-input
              v-model="form.Name"
              style="width: 200px"
              placeholder="请输入药品名"
            ></el-input>
          </el-form-item>
          <el-form-item label="药品追溯码:" label-width="150px" prop="Dtc">
                 <el-input
              v-model="form.Dtc"
              style="width: 200px"
              placeholder="请输入药品追溯码"
            ></el-input>
          </el-form-item>
              <el-button
          style="width: 20%; margin-left: 20%"
          type="primary"
          @click="baocun_add(ruleFormRef)"
          >保存</el-button
        >
        </el-form>
      </el-dialog>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import apiService from "@/services/apiService";
import { conversionUtcDate, base64ToExcelAndDownload } from "@/utils/auth";
import { v4 as uuidv4 } from "uuid";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";
import { message } from "@/utils/message";
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

//表格数据
const Data = ref<any>([]);
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页条数
const Total = ref<number>(1); //总条数
const search = ref("");
//获取药品信息
const GetList = () => {
  const params = {
    msgid: "GetPagedDrugs",
    token: getToken().accessToken,
    seq: uuidv4(),
    body: {
      pageno: currentPage.value,
      pagesize: pageSize.value,
      userid: ""
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log(res.data);
      Data.value = [];
      Data.value.push(...res.data.body.Drugs);
      Total.value = res.data.body.TotalCount;
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};
// 监听页码变化
const handleCurrentChange = val => {
  currentPage.value = val;
  GetList();
};

// 监听每页条数变化
const handleSizeChange = val => {
  pageSize.value = val;
};
//添加药品
const form = ref<any>({
  Name: "",
  Dtc: "",
  Cndc: "",
  EnglishName: "",
  ProductName: "",
  ApprovalNo: "",
  RegisterationNo: "",
  ProducerName: "",
  ImporterName: ""
});
const dialogVisible = ref(false);
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<any>>({
 Name: [
    { required: true, message: '请输入药品名', trigger: 'blur' },
  ],
  Dtc: [
    { required: true, message: '药品追溯码', trigger: 'blur' },
  ],
})
const add_yaopin = () => {
  
};
const baocun_add =  async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
     const params = {
    msgid: "AddDrug",
    token: getToken().accessToken,
    seq: uuidv4(),
    body: {
      Name: form.value.Name,
      Dtc: form.value.Dtc,
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log(res.data);
      if (res.data.code == 200) {
         dialogVisible.value = false;
      form.value = [];
              message("新增完成", { type: "success" });
      }
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
    } else {
      console.log('错误输出！', fields)
    }
  })
}

//删除药品
const del = (row: any) => {
  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const params = {
        msgid: "DeleteDrug",
        token: getToken().accessToken,
        seq: uuidv4(),
        body: {
          Id: row.Id
        }
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          GetList();
          ElMessage({
            type: "success",
            message: "删除成功"
          });
        } else if (res.data.code == 503) {
          ElMessage({
            type: "error",
            message:
              "无法删除，该药品在配药方案信息表中存在 1 个关联项，请先移除关联项"
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

const handleClose = (done: () => void) => {
  form.value = [];
   ruleFormRef.value.clearValidate()
  done();
};

onMounted(() => {
  GetList();
});
</script>

<style lang="scss" scoped></style>
